package com.onpositive.funkytable;

import com.onpositive.funkytable.impl.DefaultLayoutModel;
import com.onpositive.funkytable.impl.IGroupLayout;
import com.onpositive.funkytable.impl.LabelAndValue;
import com.onpositive.funkytable.model.ICompositeModelElement;
import com.onpositive.funkytable.model.IModelElement;

public class BuildedSectionModel {

	protected IFunkyComposite composite;
	protected Point lastMeasure;
	double weight;

	protected IControlFactory factory;
	protected ICompositeModelElement modelElement;
	protected DefaultLayoutModel lm=new DefaultLayoutModel();
	
	public BuildedSectionModel(IControlFactory f,ICompositeModelElement model){
		this.factory=f;
		this.modelElement=model;		
	}
	
	public void build(int maxWidth){
		this.composite=buildSection(factory, maxWidth, lm, modelElement);		
	}

	protected IFunkyComposite buildSection(IControlFactory factory, int width,
			DefaultLayoutModel lm, IModelElement l) {
		ICompositeModelElement pm = (ICompositeModelElement) l;
		String title = pm.title();
		IFunkyComposite createComposite2 = factory
				.createComposite(IFunkyComposite.VERTICAL);
		IFunkyTextControl section = factory.createTextElement(title);
		section.setStyle(factory.sectionStyle());
		LayoutParams params = new LayoutParams(ILayoutParams.FILL_PARENT,
				ILayoutParams.WRAP_WIDTH);
		createComposite2.add(section, params);

		int a = 0;
		IModelElement[] children2 = pm.children();
		LabelAndValue[] lv = new LabelAndValue[children2.length];
		for (IModelElement e : children2) {
			
			IFunkyTextControl lp =  e.needsLabel()?factory.createTextElement(e.title()):null;
			if(lp!=null){
			lp.setStyle(factory.style(0));
			}
			IFunkyTextControl createTextElement = factory.createTextElement(e
					.value().toString());
			lv[a] = new LabelAndValue(lp, createTextElement);
			createTextElement.setStyle(factory.style(1));
			a++;
		}
		IGroupLayout[] build = lm.build(lv, 0, lv.length - 1);
		IGroupLayout sel = null;
		double cr = 0;
		for (IGroupLayout sl : build) {
			double usageRate = sl.usageRate(width);
			
			if (cr < usageRate) {
				sel = sl;
				weight=usageRate;
			}
		}
		if (sel == null) {
			sel = build[0];
			weight=-1;
		}
		IFunkyComposite create = sel.create(width, factory);
		createComposite2.add(create, new LayoutParams(
				ILayoutParams.FILL_PARENT, ILayoutParams.WRAP_WIDTH));
		lastMeasure=createComposite2.measure(width, ILayoutParams.WRAP_WIDTH);
		return createComposite2;
	}
}
